package cn.xo68.democachehazelcast.controller;

import cn.xo68.boot.cache.common.CacheConstant;
import cn.xo68.democachehazelcast.domain.User;
import cn.xo68.democachehazelcast.service.UserSevice;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;


@RestController
public class IndexController {

    private static  final Logger logger= LoggerFactory.getLogger(IndexController.class);

    @Autowired
    private CacheManager cacheManager;

    @Autowired
    private UserSevice userSevice;

    /**
     * 读取数据
     * @param userId
     * @return
     */
    @SuppressWarnings("Duplicates")
    @GetMapping({"/",""})
    public User index(@RequestParam(name = "userId",defaultValue = "1") String userId){
        Cache cache = cacheManager.getCache(CacheConstant.CACHE_NAME_DEFAULT);
        //cache.put("a",100);

        Integer age=cache.get("a",Integer.class);
        if(age!=null){
            logger.info("=====age: {}", age);
        }

        Cache userCache = cacheManager.getCache("user");
        User user= userCache.get(userId,User.class);
        if(user!=null){
            logger.info("userId:{},userName:{}", user.getUserId(),user.getUserName());
        }

        User user2=userSevice.get(userId);
        logger.info("userId:{},userName:{}", user2.getUserId(),user2.getUserName());

        return user !=null ? user :user2;
    }

    /**
     * 添加缓存
     * @param userId
     * @param userName
     * @return
     */
    @SuppressWarnings("Duplicates")
    @GetMapping({"/addCache"})
    public String addCache(@RequestParam(name = "userId",defaultValue = "1") String userId,@RequestParam(name = "userName",defaultValue = "defaultName") String userName){

        Cache cache = cacheManager.getCache(CacheConstant.CACHE_NAME_DEFAULT);
        cache.put("a",100);

        int age=cache.get("a",Integer.class);
        logger.info(">>>=====age: {}", age);

        Cache userCache = cacheManager.getCache("user");
        userCache.put("1",new User("1","aa"));
        userCache.put("2",new User("2","aa2"));
        userCache.put("3",new User("3","aa3"));

        userSevice.add(new User(userId,userName));

        return "success";
    }


    @GetMapping({"/deleteCache"})
    public String deleteCache(@RequestParam(name = "userId",defaultValue = "1") String userId){
        userSevice.delete(userId);
        return "success";
    }
}
